/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.validate.validator;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.dspl.model.Info;
import com.google.dspl.validate.ItemReference;
import com.google.dspl.validate.violation.InfoNoInfoViolation;
import com.google.dspl.validate.violation.InfoNoNameInLanguageViolation;
import com.google.dspl.validate.violation.Violation;

import java.util.Map;

/**
 * Validation rules for {@link Info} sections.
 *
 * @author James Grimm
 */
class InfoValidator {

  private final ItemReference itemReference;
  private final boolean infoRequired;

  InfoValidator(ItemReference itemReference, boolean infoRequired) {
    this.itemReference = Preconditions.checkNotNull(itemReference);
    this.infoRequired = infoRequired;
  }

  public void validate(Info info, ImmutableList.Builder<Violation> violations) {
    if (info == null) {
      if (infoRequired) {
        violations.add(new InfoNoInfoViolation(itemReference));
      }
    } else {
      Map<String, String> names = info.getNames();
      if (names.isEmpty()) {
        violations.add(new InfoNoInfoViolation(itemReference));
      }
      for (Map.Entry<String, String> entry : names.entrySet()) {
        String language = entry.getKey();
        String name = entry.getValue();
        if (Strings.isNullOrEmpty(name)) {
          violations.add(new InfoNoNameInLanguageViolation(itemReference, language));
        }
      }
    }
  }
}
